|
This short snippet can be used to format an integer representation of a file size (in bytes) into a pretty string that includes file size metric. This snippet is a modified version of the first posting which has been refactored by Ben Laan (see comments below). The original script was copied from some other website quite a while ago, cannot remember where from, but I have used it extensively and thought I would share this useful method. If you know who the original author is please let me know. public string FormatBytes(long bytes)
{ const int scale = 1024; string[] orders = new string[] { "GB", "MB", "KB", "Bytes" }; long max = (long)Math.Pow(scale, orders.Length – 1); foreach (string order in orders) max /= scale; The original code: public string FormatBytes(int Bytes)
{ string filesize; if (Bytes >= 1073741824) { decimal size = decimal.Divide(Bytes, 1073741824); filesize = string.Format(”{0:##.##} GB”, size); } else if (Bytes >= 1048576) { decimal size = decimal.Divide(Bytes, 1048576); filesize = string.Format(”{0:##.##} MB”, size); } else if (Bytes >= 1024) { decimal size = decimal.Divide(Bytes, 1024); filesize = string.Format(”{0:##.##} KB”, size); } else if (Bytes > 0 & Bytes < 1024) { decimal size = Bytes; filesize = string.Format(”{0:##.##} Bytes”, size); } else { filesize = “0 Bytes”; } return filesize; }
You may also like
2 Responses to “Pretty Format Bytes into KB, MB or GB”Leave a Reply
|
|








This code has 4 repeating blocks! Sounds like it needs a good refactoring:
public string FormatBytesNew( long bytes )
{
const int scale = 1024;
var orders = new[] { “GB”, “MB”, “KB”, “Bytes” };
var max = (long) Math.Pow( scale, orders.Length – 1 );
foreach ( var order in orders )
{
if ( bytes > max )
return string.Format( “{0:##.##} {1}”, Decimal.Divide( bytes, max ), order );
max /= scale;
}
return “0 Bytes”;
}
Hi ben,
Thanks for the refactor!
I wasn’t completely happy with the code, especially the hard coded byte values; however I copied if from the somewhere on the web and just carried on using it. “If it ain’t broke, don’t fix it”.
I will probably give your version a try though!
Thanks